#!/usr/bin/python
# -*- coding: UTF-8 -*-

"""
@author: jiu
@contact: 643562684@qq.com
@time: 2022/3/10 14:33
"""
import openpyxl
from common.log import logger
from common.base_read_file import BASE_FILE


class Read_XLSX2(BASE_FILE):
    def __init__(self, exls_file: str, sheet: [int, str] = 1):
        super(Read_XLSX2, self).__init__(exls_file)
        self._wb = openpyxl.load_workbook(self._file)

        try:
            if isinstance(sheet, int):
                self._sheet_name = self.get_all_sheet[sheet]

            if isinstance(sheet, str):
                self._sheet_name = sheet
        except Exception as e:
            logger.exception(f"Error getting form information of sheet !")
            raise e

        self._sheet_obj = self.get_sheet_obj
        self._count_number = 0

    @property
    def get_all_sheet(self):
        """
           ['Sheet1', 'Sheet2', 'Sheet3']
        :return:  all sheet  workbook name
        """
        return self._wb.sheetnames

    @property
    def get_sheet_obj(self):
        return self._wb[self._sheet_name]

    @property
    def get_rows(self):
        # sheet object
        return list(self._sheet_obj.rows)

    @property
    def get_col(self):
        sheet = self._sheet_obj
        return len(list(sheet.columns)[0])

    @property
    def get_row_len(self):
        return len(list(self.get_rows)[0])

    @property
    def get_title(self):
        title_name = []
        if len(self.get_rows) > 1:
            _title = self.get_rows[0]
            for v in _title:
                title_name.append(v.value)

        return title_name

    @property
    def data(self):
        if not self._data:
            #  data in rows
            test_data = []
            if len(self.get_rows) > 2:
                for va in self.get_rows[1:]:
                    res = [i.value for i in va]
                    # print(res)
                    test_data.append(dict(zip(self.get_title, res)))
                return test_data
            elif len(self.get_rows) == 1:
                return self.get_title
            else:
                logger.error("Xlsx file contains no data !!!")
                raise FileNotFoundError
        return self._data

    def save(self):
        """
        file save
        :return:
        """
        self._wb.save(self._file)

    def get_col_row_num(self, row: int = -1, col: [str, int] = -1):
        """

        :param row:  1 line default title  2 lint start
        :param col:
        :return:
        """
        # rx.write_once(row=1, col=9, val='domw1')
        if not isinstance(row, int):
            raise TypeError
        if not isinstance(col, (int, str)):
            raise TypeError

        row = 2 if row == -1 else row
        if col == -1:
            if isinstance(col, str):
                col = self.get_title.index(col)
            else:
                # Last column of all columns
                col = len(self.get_title) + 1

        return row, col

    def write_once(self, row: int = -1, col: [int, str] = -1, val: str = '', title_flag: bool = True):
        """
            The default is the last line
        :param row: wirte  row
        :param col: write col
        :param val: wirte val
        :param title_flag: title  write
        :return:
        """
        res = self.get_col_row_num(row, col)

        if title_flag:
            self._sheet_obj.cell(row=res[0], column=res[1]).value = val
        else:
            self._sheet_obj.cell(row=res[0] - 1, column=res[1]).value = val
        self._wb.save(self._file)
        print("write ok!!")

    def write_many_times(self, row: int = -1, col: [int, str] = -1, val: str = 'PASS',
                         title_flag: bool = True, continuity_w: bool = True,
                         write_data: [str, list, tuple] = None):
        """

        :param row:
        :param col:
        :param val:
        :param title_flag: 是否从第2行开始 默认第一行为标签头到时候可以自己加入
        :param continuity_w:  是否连续写入
        :param write_data: 写入数据
        :return:
        """
        res = self.get_col_row_num(row, col)

        if title_flag:
            if continuity_w:  # 连续写入
                # 写入的类型判断
                if isinstance(write_data, str):
                    # 循环写入几十条数据 还没写
                    for ro in range(res[0], self.get_col):
                        self._sheet_obj.cell(row=ro, column=res[1]).value = val
                    print("wirte ok!!")
                    self.save()
                    return
                if isinstance(write_data, (list, tuple)):  # 写入规定的数据
                    for ro in range(res[0], self.get_col):
                        self._sheet_obj.cell(row=ro, column=res[1]).value = write_data[ro]
                    print("wirte ok!!")
                    self.save()
                    return
            else:
                self._sheet_obj.cell(row=res[0], column=res[1]).value = val
        else:
            self._sheet_obj.cell(row=res[0] - 1, column=res[1]).value = val

        self._count_number += 1
        print(f"Written {self._count_number} ok!, The save method is called at the end !")

